package model

import (
	"app/common/response"
	"app/pkg/db"
	"fmt"
	"math"

	"gorm.io/gorm"
)

type TakeExpressModel struct {
	CommonStruct
	UserId   int64  `gorm:"column:user_id" json:"user_id"`   //用户ID
	Name     string `gorm:"column:name" json:"name"`         //姓名
	Phone    string `gorm:"column:phone" json:"phone"`       //手机号
	Location string `gorm:"column:location" json:"location"` //地址
	Code     string `gorm:"column:code" json:"code"`         //取件码多个逗号隔开
	Note     string `gorm:"column:note" json:"note"`         //备注
	Time     string `gorm:"column:time" json:"time"`         //送出时间
	State    int8   `gorm:"column:state" json:"state"`       //1 待处理 2已完成 3异常
	Msg      string `gorm:"column:msg" json:"msg"`
}

func NewTakeExpressModel() *TakeExpressModel {
	return &TakeExpressModel{}
}

func (m *TakeExpressModel) TableName() string { return "take_express" }

func (m *TakeExpressModel) List(uid int64, keyword string, state int8, page, limit int, sTime, eTime string) (list []TakeExpressModel, paginate response.Paginate, err error) {
	paginate.Limit = limit
	paginate.Page = page
	conn, err := db.DB.MysqlDB.DefaultGormDB()
	if err != nil {
		return
	}
	conditionRst := func() func(db *gorm.DB) *gorm.DB {
		return func(db *gorm.DB) *gorm.DB {
			if uid > 0 {
				db.Where("user_id = ?", uid)
			}
			if state > 0 {
				db.Where("state = ?", state)
			}
			if sTime != "" {
				db.Where("create_time > ?", sTime)
			}
			if eTime != "" {
				db.Where("create_time <= ?", eTime)
			}
			if keyword != "" {
				db.Where("code like ?", fmt.Sprintf("%%%s%%", keyword))
			}
			return db
		}
	}()
	err = conn.Table(m.TableName()+" t").
		Scopes(PaginateScope(page, limit), conditionRst).
		Order("update_time desc").
		Find(&list).Error
	if err == nil {
		var count int64
		err = conn.Table(m.TableName() + " t").
			Scopes(conditionRst).Count(&count).Error
		if err == nil {
			paginate.Total = count
			total := float64(count) / float64(int64(limit))
			paginate.Pages = int(math.Ceil(total))
		}
	}
	return
}
